package com.ccx.coachsite.ui.manage;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.ccx.coachsite.R;
import com.ccx.coachsite.bus.AddCustomInfo;
import com.ccx.coachsite.bus.CommonBus;
import com.ccx.coachsite.bus.CustomInfo;
import com.ccx.coachsite.bus.DateParams;
import com.ccx.coachsite.bus.InviteInfo;
import com.ccx.coachsite.bus.ManageInfo;
import com.ccx.coachsite.bus.RankInfo;
import com.ccx.coachsite.bus.SalaryInfo;
import com.ccx.coachsite.bus.SharedKey;
import com.ccx.coachsite.http.BaseResp;
import com.ccx.coachsite.http.HttpRequest;
import com.ccx.coachsite.http.UrlConfig;
import com.ccx.coachsite.ui.manage.ManageSalaryView.OnQueryButtonListener;
import com.ccx.coachsite.ui.own.OwerBaseView;
import com.ccx.coachsite.ui.own.OwerMainBase;
import com.ccx.coachsite.util.CommonViewUtils;
import com.ccx.coachsite.util.ContactInfo;
import com.ccx.coachsite.util.ContactsUtil;
import com.ccx.coachsite.util.Log;
import com.ccx.coachsite.util.SharedPreferencesUtil;
import com.ccx.coachsite.util.StringUtil;

public class ManageAddCustomView extends OwerBaseView {

	private View inputTable;
	private View submitBtn;
	private View queryBtn;
	private TextView resultInfo;
	private EditText phoneTxt;
	private TextView contactCountView;
	private String mPhone;
	
	private ListView mContactList;
	private ManageContactAdapter mAdapter;
	private boolean result;
	List<ContactInfo> mList;
	
	public ManageAddCustomView(Context context, OwerMainBase superView) {
		super(context, superView);
		
		phoneTxt = (EditText)findViewById(R.id.manage_persional_custom_query);
		queryBtn = findViewById(R.id.manage_personal_query_customer_button);
		resultInfo = (TextView)findViewById(R.id.manage_personal_result_info_label);
		inputTable = findViewById(R.id.manage_personal_custom_input_table);
		submitBtn = findViewById(R.id.manage_personal_custom_input_submit);
		
		//queryBtn.setOnClickListener(new OnSubmitButtonListener());
		queryBtn.setOnClickListener(new OnQueryButtonListener());
		//submitBtn.setOnClickListener(new OnSubmitButtonListener());
		
		contactCountView = (TextView)findViewById(R.id.manage_contact_count);
		mContactList = (ListView)findViewById(R.id.manage_contact_list);
		//clearData();
		//loadData();
		/*
		if(mList.size() > 0)
		{
			loadData();
		}
		*/
	}
	
	protected boolean onLoadData() {
		mList = ContactsUtil.getContactinfoList(mContext);
		if(mList.size() > 0)
		{
			result = ManageProvider.getInstance().checkContacts(mContext, mList);
		}
		
		return true;
	}

	protected void doRefreshDataSuccess() {
		if(result)
		{
			mAdapter = new 	ManageContactAdapter(mContext, mList);
			mContactList.setDivider(mContext.getResources().getDrawable(
					R.drawable.ower_sip_line));
			mContactList.setAdapter(mAdapter);
			contactCountView.setText(mList.size()+"");
		}
	}
	
	private boolean checkInput() {
		Animation shake = AnimationUtils.loadAnimation(mContext, R.anim.shake);
		
		String phone = phoneTxt.getText().toString().trim();
		
		if (StringUtil.isEmpty(phone)) {
			CommonViewUtils.showErrorByEditText(phoneTxt, "请输入天翼手机号码", shake);
			return false;
		}

		if (!StringUtil.isMMobile(phone)) {
			CommonViewUtils.showErrorByEditText(phoneTxt,
					"请输入正确的天翼号码", shake);
			return false;
		}
		return true;
	}
	
	private void sendRequest() {
		if (!checkInput())
			return;

		CommonViewUtils.hideKeyboard((Activity)mContext);
		
		if (!CommonViewUtils.isNetConnectionAvailable(mContext)) {
			Toast.makeText(mContext, R.string.login_network_error, Toast.LENGTH_SHORT).show();
			return;
		}
		
		mPhone = phoneTxt.getText().toString().trim();
//		queryBus qb = new queryBus(mContext);
//		qb.setQueryCustomParam(mPhone);
//		qb.doTask();
		
		addCustomBus qb = new addCustomBus(mContext);
		String userId = SharedPreferencesUtil.getValue(mContext,
				SharedKey.Shared_UserId_Key, "");
		qb.setShowTip(false);
		qb.setAddCustomParam(mPhone, userId, 0, 0, 0, "");
		qb.doTask();
	}
	
	class OnQueryButtonListener implements OnClickListener {
		@Override
		public void onClick(View v) 
		{
			sendRequest();
		}
	}
	
	private void doSubmit() {
		if (!checkInput())
			return;
		
		CommonViewUtils.hideKeyboard((Activity)mContext);
		
		if (!CommonViewUtils.isNetConnectionAvailable(mContext)) {
			Toast.makeText(mContext, R.string.login_network_error, Toast.LENGTH_SHORT).show();
			return;
		}
		
		mPhone = phoneTxt.getText().toString().trim();
		addCustomBus qb = new addCustomBus(mContext);
		qb.setShowTip(false);
		RadioGroup rg1 = (RadioGroup)findViewById(R.id.manage_personal_radiogroup_sex);
		int sexId = rg1.getCheckedRadioButtonId();
		int sex = 1;
		if(sexId == R.id.manage_personal_radioMale)
			sex = 0;
			
		rg1 = (RadioGroup)findViewById(R.id.manage_personal_radiogroup_age);
		int ageId = rg1.getCheckedRadioButtonId();
		int age = 0;
		
		if(sexId == R.id.manage_personal_radioMale)
			age = 1;
		else if(sexId == R.id.manage_personal_radioMale)
			age = 2;
		
		String userId = SharedPreferencesUtil.getValue(mContext,
				SharedKey.Shared_UserId_Key, "");
		qb.setAddCustomParam(mPhone, userId, 0, 0, 0, "");
		qb.doTask();
	}
	
	class OnSubmitButtonListener implements OnClickListener {
		@Override
		public void onClick(View v) 
		{
			doSubmit();
		}
	}
	
	private void clearData()
	{
		resultInfo.setVisibility(View.GONE);
		inputTable.setVisibility(View.GONE);
		submitBtn.setVisibility(View.GONE);
		phoneTxt.setText("");
	}
	
	private void onQuery(boolean isApply, String Desc)
	{
		if(isApply)
		{
			AlertDialog.Builder renameDialog=new AlertDialog.Builder(mContext);
			renameDialog.setTitle("提示");
			renameDialog.setMessage(Desc)
			.setPositiveButton(R.string.common_button_confirm, new DialogInterface.OnClickListener() {	
				@Override
				public void onClick(DialogInterface dialog, int which) {
					
				}
			})
			.create().show();	
		}
		else
		{
			AlertDialog.Builder renameDialog=new AlertDialog.Builder(mContext);
			renameDialog.setTitle("提示");
			renameDialog.setMessage(Desc)
			.setPositiveButton("邀请好友", new DialogInterface.OnClickListener() {	
				@Override
				public void onClick(DialogInterface dialog, int which) {
					doSubmit();
				}
			})
			.setNegativeButton(R.string.common_button_cancell, new DialogInterface.OnClickListener() {	
				@Override
				public void onClick(DialogInterface dialog, int which) {
					
				}
			})
			.create().show();	
		}
	}
	
	class queryBus extends CommonBus{

		public queryBus(Context context) {
			super(context);
		}
		
		@Override
		public void callBack(int taskType, BaseResp response, String responseJson) {
			super.callBack(taskType, response, responseJson);
			
			if(response.isSuccess())
			{
				boolean isApply = true;
				JSONObject jsonObject;
				try {
					jsonObject = new JSONObject(responseJson);

					JSONArray respsonArray = jsonObject.optJSONArray("response");
					JSONObject respsonObject = null;
					if(respsonArray != null && respsonArray.length() > 0)
					{
						respsonObject = respsonArray.getJSONObject(0);
					}
					else
					{
						respsonObject = jsonObject.optJSONObject("response");
					}
					
					if(respsonObject != null && !respsonObject.isNull("isApply"))
					{
						isApply = respsonObject.getInt("isApply") != 0;
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
				if(!isApply)
				{
					String result = "号码 " + mPhone + " 用户尚未被邀请，您可以邀请他。";
					onQuery(isApply, result);
//					resultInfo.setText(result);
//					resultInfo.setVisibility(View.VISIBLE);
//					inputTable.setVisibility(View.GONE);
//					//inputTable.setVisibility(View.VISIBLE);
//					submitBtn.setVisibility(View.VISIBLE);
				}
				else
				{
					String result = "号码 " + mPhone + " 用户已经被邀请，请重新邀请其他用户号码。";
					onQuery(isApply, result);
//					resultInfo.setText(result);
//					resultInfo.setVisibility(View.VISIBLE);
//					inputTable.setVisibility(View.GONE);
//					submitBtn.setVisibility(View.GONE);
				}
			}
			else
			{
				String result = "号码 " + mPhone + " 输入有误或者号码不存在，请重新输入。";
				onQuery(true, result);
//				resultInfo.setText(result);
//				resultInfo.setVisibility(View.VISIBLE);
//				inputTable.setVisibility(View.GONE);
//				submitBtn.setVisibility(View.GONE);
			}
		}
	}
	
	private void doAddCustom(BaseResp response)
	{
		boolean isSuccess = false;
		String message = "添加出错";
		try {
			JSONObject jsonObject = new JSONObject(response.getHttpResult());
			message = jsonObject.optString("response");
			if(StringUtil.isEmpty(message))
			{
				message = response.getDesc();
				/*
				JSONObject respsonObject = jsonObject.getJSONObject("response");
				if(respsonObject != null)
				{
					message = respsonObject.optString("message");
				}
				*/
			}
			if (response.isSuccess()) {
				isSuccess = true;
			}
		} catch (Exception e) {
			isSuccess = false;
			message = "添加出错";
			Log.e(e.getMessage(), e);
		} finally {
		}
		
		if(!isSuccess)
		{
			AlertDialog.Builder renameDialog=new AlertDialog.Builder(mContext);
			renameDialog.setTitle("添加失败");
			renameDialog.setMessage(message)
			.setPositiveButton("确定", new DialogInterface.OnClickListener() {	
				@Override
				public void onClick(DialogInterface dialog, int which) {
					phoneTxt.setText("");
				}
			})
			.create().show();	
		}
		else
		{
			AlertDialog.Builder renameDialog=new AlertDialog.Builder(mContext);
			renameDialog.setTitle("添加成功");
			renameDialog.setMessage(message)
			.setPositiveButton("完成并返回", new DialogInterface.OnClickListener() {	
				@Override
				public void onClick(DialogInterface dialog, int which) {
					mSuperView.onBackClick();
				}
			})
			.setNegativeButton("继续添加", new DialogInterface.OnClickListener() {	
				@Override
				public void onClick(DialogInterface dialog, int which) {
					phoneTxt.setText("");
				}
			})
			.create().show();	
		}
	}
	
	private void doAddSuccess(BaseResp response)
	{
		boolean isSuccess = false;
		
		AddCustomInfo ainfo = new AddCustomInfo();
		try {
			
			if (response.isSuccess()) {
				JSONObject jsonObject = new JSONObject(response.getHttpResult());
				JSONObject respsonObject = jsonObject.getJSONObject("response");
				ainfo.setCanInviteNum(respsonObject.getInt("leftCount"));
				JSONArray respsonList = respsonObject.getJSONArray("userRelationList");
				if (respsonList != null && respsonList.length() > 0) {
					List<InviteInfo> rankList = new ArrayList<InviteInfo>();
					for (int i = 0; i < respsonList.length(); i++) {
						JSONObject obj = respsonList.getJSONObject(i);
						InviteInfo info = new InviteInfo();
						info.setInviteName(obj.getString("username"));
						info.setInviteTime(obj.getString("addTime"));
						rankList.add(info);
					}

					ainfo.setInviteList(rankList);
				}
				isSuccess = true;
			}
		} catch (Exception e) {
			isSuccess = false;
			Log.e(e.getMessage(), e);
		} finally {
		}

		if(isSuccess)
		{
			if(mAdapter != null)
				mAdapter.doDeleteContact(mPhone);
			
			//loadData();
			clearData();
			SwitchView(ManageKey.ll_manage_add_custom_result, ainfo);
		}
		
	}
	
	class addCustomBus extends CommonBus{

		public addCustomBus(Context context) {
			super(context);
		}
		
		@Override
		public void callBack(int taskType, BaseResp response, String responseJson) {
			super.callBack(taskType, response, responseJson);
			
			doAddCustom(response);
//			if(response.isSuccess())
//			{
//				doAddSuccess(response);
//			}
//			else
//			{
//
//			}
		}
	}
}
